from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.urls import reverse
from django.http import FileResponse
import os, re
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.utils.encoding import escape_uri_path

pictures = ['.BMP', '.PNG', '.TIF', '.GIF', '.JPEG', '.bmp', '.png', '.tif', '.gif', '.jpeg', '.jpg', '.JPG']

videos = ['.AVI', '.MOV', '.RMVB', '.RM', '.FLV', '.MP4', '.3GP', '.avi', '.mov', '.rmvb', '.rm', '.flv', '.mp4', '.3gp']

audios = ['.cd', '.wave', '.aiff', '.mpeg', '.mp3', '.mpeg-4', '.midi', '.wma', '.realaudio', '.vqf', '.oggvorbis', '.amr', '.ape', '.flac', '.aac', '.CD', '.WAVE', '.AIFF', '.MPEG', '.MP3', '.MPEG-4', '.MIDI', '.WMA', '.REALAUDIO', '.VQF', '.OGGVORBIS', '.AMR', '.APE', '.FLAC', '.AAC']

extensions = ['.odt', '.toast', '.exe', '.apk', '.rtf', '.pdf', '.wpl', '.db', '.7z', '.csv', '.vob', '.flc', '.dmp', '.f4v', '.m2t', '.ps', '.cpl', '.pkg', '.bin', '.rar', '.cab', '.sys', 'if', '.bak', '.ico', '.lavf', '.cgi', '.odp', '.dat', '.pps', '.bat', '.iso', '.wsf', '.ts', '.doc', '.ram', '.mpe', '.ogg', '.fli', '.cur', '.tmp', '.dv', '.zip.m2ts', '.pptx', '.ai', '.cpk', '.tex', '.ttf', '.asf', '.zip', '.arj', '.eml', '.m4v', '.mod', '.tar', '.drv', '.mid', '.log', '.com', '.email', '.msg', '.dll', '.wpd', '.mts', '.oft', '.wmv', '.msi', '.lnk', '.mpg', '.dirac', '.qt', '.dat', '.key', '.dmg', '.pst', '.rpm', '.icns', '.mpa', '.ppt', '.sql', '.webm', '.otf', '.3g2', '.swf', '.ost', '.div', '.deb', '.svg', '.vcf', '.tar.gz', '.cda', '.jar', '.vcd', '.mod', '.fnt', '.mdb', '.gadget', '.mkv', '.z', '.psd', '.sav', '.wav', '.fon', '.divx', '.emlx']

ptn01 = re.compile(r'^\..+')
ptn02 = re.compile(r'[^/]+/$')
# absolute_base_path = '/root/'
absolute_base_path = '/home/share_samba/game/dw'

def convert(n):
    if n >= 1024*1024:
        return str(round(n/1024/1024, 1)) + 'M'
    elif n >=1024:
        return str(round(n/1024, 1)) + 'K'
    else:
        return str(n)

# @login_required(login_url="/file/login/")
@csrf_exempt
def fileView(request):
    base_path = '/'
    if request.method == 'POST':
        doc_type = request.POST['doc_type']
        if doc_type == '1':
            base_path = request.POST['base_path']
            base_path = base_path+'' if base_path.endswith('/') else base_path+'/'
            filename = request.POST['filename']
            file = open(absolute_base_path + base_path + filename, 'rb')
            response = FileResponse(file)
            response['Content-Type'] = 'application/octet-stream'
            response["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(filename))
            return response
        elif doc_type == '2':
            base_path = request.POST['base_path'] + request.POST['dirname']
            base_path = base_path+'' if base_path.endswith('/') else base_path+'/'
            if not request.POST['dirname'] :
                base_path = re.sub(ptn02, '', base_path)
            files = os.path.os.listdir(absolute_base_path + base_path)
            files = list(filter(lambda x:not re.match(ptn01, x), files))
            dirs = filter(lambda x:os.path.isdir(absolute_base_path + base_path +x), files)
            files = list(filter(lambda x:os.path.isfile(absolute_base_path + base_path +x), files))
            file_size = [os.path.getsize(absolute_base_path + base_path + f) for f in files]
            file_size = map(convert, file_size)
            files = dict(zip(files, file_size))
            return render(request, 'file.html', locals())
        elif doc_type == '3':
            base_path = request.POST['base_path']
            base_path = base_path+'' if base_path.endswith('/') else base_path+'/'
            filename = request.POST['filename']
            if ('.'+filename.rsplit('.')[-1] in pictures):
                try:
                    os.system('rm -rf ' + 'media/' + filename)
                except:
                    pass
                file_path = os.path.abspath(filename)
                os.system('ln -s ' + absolute_base_path + base_path + filename + ' ' +  'media/')
                text = "<img src=\'/media/" + filename + "\'>"
                status = '3'
            elif ('.'+filename.rsplit('.')[-1] in videos):
                try:
                    os.system('rm -rf ' + 'media/' + filename)
                except:
                    pass
                file_path = os.path.abspath(filename)
                os.system('ln -s ' + absolute_base_path + base_path + filename + ' ' +  'media/')
                text = "<video  src=\'/media/" + filename +"\'  width='1000px' controls autoplay loop class='text-center'>"
                status = '4'
            elif ('.'+filename.rsplit('.')[-1] in audios):
                try:
                    os.system('rm -rf ' + 'media/' + filename)
                except:
                    pass
                file_path = os.path.abspath(filename)
                os.system('ln -s ' + absolute_base_path + base_path + filename + ' ' +  'media/')
                text = "<audio controls><source src=\'/media/" + filename + "\' autoplay loop></audio>"
                status = '5'
            else:
                try:
                    if( '.'+filename.rsplit('.')[-1] in extensions):
                        raise Exception
                    text = open(absolute_base_path + base_path + filename).read()
                    status = '1'
                except:
                    text = '{} \n\tis not a txt file.'.format(filename)
                    status = '2'
            return JsonResponse({'text': text, 'status':status})
        else:
            return HttpResponse('2')
    if request.method == 'GET':
        files = os.path.os.listdir(absolute_base_path + base_path)
        files = list(filter(lambda x:not re.match(ptn01, x), files))
        dirs = filter(lambda x:os.path.isdir(absolute_base_path + base_path +x), files)
        files = list(filter(lambda x:os.path.isfile(absolute_base_path + base_path +x), files))
        file_size = [os.path.getsize(absolute_base_path + base_path + f) for f in files]
        file_size = map(convert, file_size)
        files = dict(zip(files, file_size))
        return render(request, 'file.html', locals())

@csrf_exempt
def upload_file(request):
    if request.method == "POST":    # 请求方法为POST时，进行处理
        myFile =request.FILES.get("myfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        base_path = request.POST['base_path']
        if not myFile:
            return HttpResponse("no files for upload!")
        destination = open(absolute_base_path + base_path + myFile.name, 'wb+')    # 打开特定的文件进行二进制的写操作
        for chunk in myFile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()
        base_path = request.POST['base_path']
        files = os.path.os.listdir(absolute_base_path + base_path)
        files = list(filter(lambda x:not re.match(ptn01, x), files))
        dirs = filter(lambda x:os.path.isdir(absolute_base_path + base_path +x), files)
        files = list(filter(lambda x:os.path.isfile(absolute_base_path + base_path +x), files))
        file_size = [os.path.getsize(absolute_base_path + base_path + f) for f in files]
        file_size = map(convert, file_size)
        files = dict(zip(files, file_size))
        return render(request, 'main.html', locals())
    else:
        return redirect(reverse('file:file'))

def testView(request):
    return render(request, 't1.html', locals())

def foundationView(request):
    return render(request, 'foundation.html', locals())
